package com.kadron.datamodel;

import java.util.List;

import javax.persistence.EntityManager;

import com.kadron.dao.KItemDAO;
import com.kadron.entity.Item;

public class KIModelDataProvider implements KDataProvider {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4707252300895840420L;
	
	private KModelCreator creator;
	private KItemDAO itemDAO;
	
	public KIModelDataProvider(KModelCreator creator, KItemDAO itemDAO) {
		super();
		this.creator = creator;
		this.itemDAO = itemDAO;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Long> getItemsByRange(Integer integer, int numberOfRows,
			Object object, boolean b) {
		EntityManager em = itemDAO.getEntityManager();
		return em.createQuery("SELECT e.id FROM Item e ORDER BY e.id ASC").setFirstResult(integer).setMaxResults(numberOfRows).getResultList();
	}

	@Override
	public KModel getItemById(Long id, KModelCreator creator) {
		return creator.create(id);
	}

	@Override
	public int getRowCount() {
		EntityManager em = itemDAO.getEntityManager();
		Long count = (Long) em.createQuery("SELECT COUNT(e.id) FROM Item e ").getSingleResult();
		return (count == null) ? 0 : count.intValue() ;
	}

	@Override
	public boolean hasItemWithId(Long id) {
		return itemDAO.exists(id, Item.class);
	}

	@Override
	public KModelCreator getCreator() {
		return creator;
	}

}
